package com.woniuxy.controller;

import com.woniuxy.entity.ResponseEntity;
import com.woniuxy.entity.User;
import com.woniuxy.service.AuthService;
import com.woniuxy.utils.JWTUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

/**
 * @Author: 马宇航
 * @Todo: TODO
 * @DateTime: 25/08/06/星期三 12:14
 * @Component: 成都蜗牛学苑
 **/
@RestController
@RequestMapping("auth")
public class AuthController {
    @Autowired
    AuthService authService;
    @Autowired
    RedisTemplate redisTemplate;
    @PostMapping("/login")
    public ResponseEntity login(@RequestBody User user) {
        User loginUser = authService.login(user);
        if (loginUser != null) {
            //登录成功，生成双token
            String token = JWTUtils.createToken(loginUser.getUsername());
            //生成uuid的token：分布式情况，雪花算法，分布式的唯一id
            String refreshToken = UUID.randomUUID().toString();
            loginUser.setPassword("");
            //把刷新token当作key，存入redis的hash
            Map<String,Object> userInfo = new HashMap<>();
            userInfo.put("token",token);
            userInfo.put("refreshToken",refreshToken);
            userInfo.put("user",loginUser);
            redisTemplate.opsForHash().putAll(refreshToken,userInfo);
            //设置过期时间:根据工具类的过期时间统一配置
            redisTemplate.expire(refreshToken,JWTUtils.REFRESH_TOKEN_EXPIRE_TIME, TimeUnit.SECONDS);
            ResponseEntity responseEntity = new ResponseEntity(refreshToken);
            responseEntity.put("username",loginUser.getUsername());
            responseEntity.put("token",token);
            return responseEntity;
        }else {
            return ResponseEntity.ERROR;
        }
    }
}
